package com.google.code.donkirkby.commandlet;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Controller
{
	private static Log log = LogFactory.getLog(Controller.class);
	
	public static void main(String[] args)
	{
		try
		{
			log.info("argument count = " + args.length);
			BeanFactory beanFactory = 
				new ClassPathXmlApplicationContext("/spring.xml");
			DialogImpl dialog = (DialogImpl) beanFactory.getBean("dialog", DialogImpl.class);
			
			if (args.length > 0 && args[0].equalsIgnoreCase("validate"))
			{
				// we were just asked to validate the spring config file.
				// we've done that, so exit.
				return;
			}
			
			dialog.displayVersion();
            boolean isDone;
			try
			{
                do
                {
                    try
                    {
                        Command command = dialog.chooseCommand();
                        isDone = !command.execute();
                        dialog.display("Command completed.");
                    }catch(Exception e)
                    {
                        String msg = "Command failed.";
                        log.error(msg, e);
                        dialog.display(msg);
                        isDone = false;
                    }
                }while(!isDone);
			}finally
			{
				//connection.close();
			}
		} catch (Exception e)
		{
			log.error("Fatal exception.", e);
			System.exit(-1);
		}
	}
}
